﻿using System;
using System.Windows.Interactivity;
using SL8.SL.Controls;
using SL8.SL.Extensions;
using System.Windows;
using System.Windows.Input;

namespace SL8.SL.Actions
{
    public class SearchConditionCollectAction : TargetedTriggerAction<FrameworkElement>
    {
        public System.Type EntityType
        {
            get
            {
                return (Type)base.GetValue(SearchConditionCollectAction.EntityTypeProperty);
            }

            set
            {
                base.SetValue(SearchConditionCollectAction.EntityTypeProperty, value);
            }
        }

        public static readonly DependencyProperty EntityTypeProperty = DependencyProperty.Register("EntityType",
            typeof(Type),
            typeof(SearchConditionCollectAction), null);

        public ICommand Command
        {
            get
            {
                return (ICommand)base.GetValue(SearchConditionCollectAction.CommandProperty);
            }

            set
            {
                base.SetValue(SearchConditionCollectAction.CommandProperty, value);
            }
        }

        public static readonly DependencyProperty CommandProperty = DependencyProperty.Register("Command",
            typeof(ICommand),
            typeof(SearchConditionCollectAction), null);

        protected override void Invoke(object parameter)
        {
            if (this.Command == null)
            {
                return;
            }

            if (this.Target == null || this.Target == this.AssociatedObject)
            {
                SearchConditionCollectPanel searchConditionCollectPanel = this.AssociatedObject.GetParent<SearchConditionCollectPanel>();

                if (searchConditionCollectPanel != null)
                {
                    if (this.Command.CanExecute(null))
                    {
                        this.Command.Execute(searchConditionCollectPanel.GetSearchExpressionByEntityType(this.EntityType));
                    }
                }
            }
            else
            {
                SearchConditionCollectPanel searchConditionCollectPanel = this.Target as SearchConditionCollectPanel;
                if (searchConditionCollectPanel != null && this.Command.CanExecute(null))
                {
                    this.Command.Execute(searchConditionCollectPanel.GetSearchExpressionByEntityType(this.EntityType));
                }
            }
        }
    }
}
